package com.bwda.dsrs.filecenter.controller;

import com.bwda.dsrs.filecenter.annotations.NeedRole;
import com.bwda.dsrs.filecenter.aspect.LogTypeEnum;
import com.bwda.dsrs.filecenter.aspect.Loggable;
import com.bwda.dsrs.filecenter.domain.BusinessConstants;
import com.bwda.dsrs.filecenter.domain.condition.sensitivelevel.SensitiveLevelCondition;
import com.bwda.dsrs.filecenter.domain.condition.sensitiverule.SensitiveRuleCondition;
import com.bwda.dsrs.filecenter.domain.condition.sensitivewords.SensitiveWordsCondition;
import com.bwda.dsrs.filecenter.domain.exception.BusinessServiceException;
import com.bwda.dsrs.filecenter.domain.form.sensitivewords.SensitiveWordsCreateForm;
import com.bwda.dsrs.filecenter.domain.form.sensitivewords.SensitiveWordsQueryForm;
import com.bwda.dsrs.filecenter.domain.form.sensitivewords.SensitiveWordsUpdateForm;
import com.bwda.dsrs.filecenter.domain.po.sensitivelevel.SensitiveLevelPo;
import com.bwda.dsrs.filecenter.domain.po.sensitiverule.SensitiveRulePo;
import com.bwda.dsrs.filecenter.domain.po.sensitivewords.SensitiveWordsPo;
import com.bwda.dsrs.filecenter.domain.vo.sensitivewords.SensitiveWordsVo;
import com.bwda.dsrs.filecenter.service.SensitiveLevelService;
import com.bwda.dsrs.filecenter.service.SensitiveRuleService;
import com.bwda.dsrs.filecenter.service.SensitiveWordsService;
import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.CopyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 业务配置--敏感字段--控制类
 *
 * @author zhangyinmei
 * @date 2019年4月27日
 */
@RestController
@RequestMapping("/b/sensitivewords")
@Api(value = "/b/sensitivewords", tags = "敏感字段")
public class SensitiveWordsController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SensitiveWordsController.class);

	@Autowired
	private SensitiveWordsService sensitiveWordsService;
	@Autowired
	private SensitiveLevelService sensitiveLevelService;

	@Autowired
	private SensitiveRuleService sensitiveRuleService;


	/**
	 * 查询敏感字段列表(带分页)
	 *
	 * @param form
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("sysadminrole")
	@Loggable(descp = "查询敏感字段列表",type = LogTypeEnum.QUERY,include = "")
	@ApiOperation(value = "查询敏感字段列表(带分页)",notes = "查询敏感字段列表(带分页)",httpMethod = "GET")
	@RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreCutPageResponse<SensitiveWordsVo>> queryPageList(@ModelAttribute@Valid SensitiveWordsQueryForm form) throws BusinessServiceException {
		logger.info("分页查询敏感字段");
		SensitiveWordsCondition condition = this.getConditionByQueryForm(form);
		condition.setDelFlag(BusinessConstants.DelFlag.NOT_DELETED);
		List<SensitiveWordsVo> voList = new ArrayList<>();
		int count = sensitiveWordsService.queryCount(condition);
		if (count > BusinessConstants.NumberConstant.ZERO) {
			List<SensitiveWordsPo> poList = sensitiveWordsService.queryList(condition);
			voList = CopyUtil.transfer(poList, SensitiveWordsVo.class);
		}
		return getSuccessResult(getPageResponse(form, count, voList));
	}

	/**
	 * 新增敏感字段
	 *
	 * @param form
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("sysadminrole")
	@Loggable(descp = "新增敏感字段",type = LogTypeEnum.CREATE,include = "")
	@ApiOperation(value = "新增敏感字段",notes = "新增敏感字段",httpMethod = "POST")
	@RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<SensitiveWordsVo> add(@ModelAttribute@Valid SensitiveWordsCreateForm form, HttpServletRequest request) throws BusinessServiceException {
		logger.info("新增敏感字段");
		SensitiveWordsPo po = CopyUtil.transfer(form, SensitiveWordsPo.class);
		//获取系统当前时间
		Date currentTime = new Date();
		//设置创建时间
		po.setCreateTime(currentTime);
		//设置是否删除为未删除
		po.setDelFlag(BusinessConstants.DelFlag.NOT_DELETED);
		//设置状态为在用
		po.setStatus(BusinessConstants.StateType.ENABLE);
		//设置创建人编码
		String currentUserCode = getUserCode();
		po.setCreateUserCode(currentUserCode);
		sensitiveWordsService.insert(po);
		SensitiveWordsVo vo = CopyUtil.transfer(po, SensitiveWordsVo.class);
		return getSuccessResult(vo);
	}

	/**
	 * 修改敏感字段
	 *
	 * @param form
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("sysadminrole")
	@Loggable(descp = "修改敏感字段",type = LogTypeEnum.UPDATE,include = "")
	@ApiOperation(value = "修改敏感字段",notes = "修改敏感字段",httpMethod = "POST")
	@RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity update(@ModelAttribute@Valid SensitiveWordsUpdateForm form, HttpServletRequest request) throws BusinessServiceException {
		logger.info("修改敏感字段");
		if (form.getStatus()==1){
			SensitiveRuleCondition condition = new SensitiveRuleCondition();
			condition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
			condition.setWordId(form.getId());
			List<SensitiveRulePo> list =sensitiveRuleService.queryList(condition);
			if (list!=null&&list.size()!=0){
				return getFailResult("该敏感字段已被使用，无法禁用");
			}
		}
		SensitiveWordsPo po = CopyUtil.transfer(form, SensitiveWordsPo.class);
		//设置更新时间
		po.setUpdateTime(new Date());
		//设置更新人编码
		String currentUserCode = getUserCode();
		po.setUpdateUserCode(currentUserCode);
		sensitiveWordsService.update(po);
		return getSuccessResult();
	}

	/**
	 * 删除敏感字段
	 *
	 * @param id
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("sysadminrole")
	@Loggable(descp = "删除敏感字段",type = LogTypeEnum.DELETE,include = "")
	@ApiOperation(value = "删除敏感字段",notes = "删除敏感字段",httpMethod = "POST")
	@RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity delete(@Valid @RequestParam(value = "id") List<Integer> id) throws BusinessServiceException {
		logger.info("逻辑删除敏感字段");
		if(id==null||id.size()==0){
			return getFailResult("参数错误");
		}

		for(Integer item:id){
			//如果敏感字段在用，就不给删，目前应该就敏感等级中用到
			checkCanDeleteSensitiveWords(item);
		}


		sensitiveWordsService.batchDelete(id);
		return getSuccessResult();
	}

	/**
	 * 检查敏感字段是否可删除
	 * @param id
	 */
	private void checkCanDeleteSensitiveWords(Integer id) throws BusinessServiceException {
		//查询所有在用的敏感等级
		SensitiveLevelCondition levelCondition = new SensitiveLevelCondition();
		levelCondition.setDelFlag(BusinessConstants.DelFlag.NOT_DELETED);
		levelCondition.setSensitiveState(BusinessConstants.SensitiveLevelState.VALID);
		List<SensitiveLevelPo> levelPoList = sensitiveLevelService.queryList(levelCondition);
		for(SensitiveLevelPo levelPo:levelPoList){
			//根据敏感等级匹配规则
			SensitiveRuleCondition	ruleCondition = new SensitiveRuleCondition();
			ruleCondition.setSensitiveId(levelPo.getId());
			List<SensitiveRulePo> rulePoList = sensitiveRuleService.queryList(ruleCondition);
			//遍历敏感等级规则集合，根据敏感字段ID获取敏感字段信息
			for(SensitiveRulePo sensitiveRulePo : rulePoList){
				if(id.equals(sensitiveRulePo.getWordId())){
					throw new BusinessServiceException("敏感字段正在被使用，无法删除");
				}
			}

		}
	}

	/**
	 * SensitiveWordsQueryForm转换为SensitiveWordsCondition
	 *
	 * @param form
	 * @return
	 */
	private SensitiveWordsCondition getConditionByQueryForm(SensitiveWordsQueryForm form) {
		SensitiveWordsCondition condition = CopyUtil.transfer(form, SensitiveWordsCondition.class);
		return condition;
	}

}